package cn.liziguo;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 画布(主要逻辑)
 *
 * @author Liziguo
 * @date 2025-04-08
 */
public class MyPanel extends JPanel {
    /**
     * 雪花集合
     */
    private final Map<Snowflake, Object> map = new ConcurrentHashMap<>();
    /**
     * 雪花图片
     */
    private final BufferedImage image;
    /**
     * fps
     */
    private final int fps;
    /**
     * 越小雪花越多
     */
    private final int snowflakeAdd;

    public MyPanel(BufferedImage image, int fps, int snowflakeAdd) {
        this.image = image;
        this.fps = fps;
        this.snowflakeAdd = snowflakeAdd;
        // 设为透明的
        this.setOpaque(false);
        // 启动线程
        new Thread(this::run).start();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        for (Snowflake x : map.keySet()) {
            g.drawImage(image, (int) x.getX(), (int) x.getY(), x.getW(), x.getH(), null);
        }
    }

    private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void run() {
        // 每秒帧数
        int time = 1000 / fps;
        int i = 0;
        while (true) {
            long startTime = System.currentTimeMillis();
            if (++i >= snowflakeAdd) {
                // map当set用 value是什么无所谓
                map.put(new Snowflake(), image);
                i = 0;
            }
            // 调用所有雪花的run方法
            for (Snowflake x : map.keySet()) {
                x.run();
                // 如果雪花超出屏幕范围的话就从集合中删掉
                // 雪花是从右上角往左上角飘的 所以只判断两个点
                if (x.getX() + x.getW() < 0 || x.getY() > WinMain.SCREEN_HEIGHT) {
                    map.remove(x);
                }
            }
            repaint();
            long diff = System.currentTimeMillis() - startTime;
            long sleep = time - diff;
            if (sleep > 0) {
                sleep(sleep);
            }
        }
    }
}